const toolHelper = require("../utils/toolHelper.js");
import {getApi} from '../utils/dataHelper'
const Base64 = require("../utils/base64");



let header = {
  'Accept': 'application/json',
  'content-type': 'application/json',
  'Authorization': ''
}


function queryData(data) {
  var str = '';
  for (var i in data) {
    str += i + "=" + data[i] + '&';
  }
  if (str) {
    str = '?' + str;
    str = str.substr(0, str.length - 1);
  }
  return str;
}

const http = {};
http.get = function get(url, data, cb) {
  console.log(getApi(), url, data)
  if (wx.getStorageSync('token')) {
    header['Authorization'] = `Bearer ${wx.getStorageSync('token')}`
  }
  wx.showToast({
    title: '加载中',
  })
  wx.request({
    url: getApi() + url + queryData(data),
    method: 'get',
    header: header,
    success: function (res) {
      console.log(res.data)
      wx.hideToast();
      let resData = res.data;
      switch (res.data.code) {
        case 200:
          toolHelper.isFunction(cb) && cb(resData);
          break;
        case 401:
          wx.showToast({
            icon: "none",
            title: '请重新登录'
          });
          setTimeout(() => {
            wx.clearStorage()
            wx.reLaunch({
              url: '/pages/my/index/index',
            })
          })
          break;
        default:
          wx.showToast({
            icon: "none",
            title: resData.msg
          });
      }
    },
    fail(res) {
      wx.showToast({
        title: '请求出错，请联系相关人员',
        icon: 'none'
      })
      wx.hideLoading();
    },
    complete(res) {
      wx.hideLoading();
    }
  })
}

http.post = function post(url, data, cb) {
  console.log(getApi(), url, data)
  if (wx.getStorageSync('token')) {
    header['Authorization'] = `Bearer ${wx.getStorageSync('token')}`
  }
  wx.request({
    url: getApi() + url,
    method: 'post',
    data: data,
    header: header,
    formData: data,
    success: function (res) {
      let resData = res.data;
      switch (res.data.code) {
        case 200:
          toolHelper.isFunction(cb) && cb(resData);
          break;
        case 401:
          wx.showModal({
            title: '错误信息',
            content: resData.msg,
            confirmText: '知道了',
            showCancel: false,
            success(res1) {
              if (res1.confirm) {
                wx.clearStorage()
                wx.reLaunch({
                  url: '/pages/my/index/index',
                })
              }
            }
          })
          break;
        default:
          wx.showToast({
            icon: "none",
            title: resData.msg
          });
      }
    },
    fail(err) {
      wx.showToast({
        title: '请求出错，请联系相关人员',
        icon: 'none'
      })
    },
    complete(res) {
    }
  });
}


module.exports = http;